/**
 * 读取组织信息列表
 */

function orgnizerUserData(module_name){

    var table = new Bstable();


    //读取组织信息列表
    $.ajax({
        type:"GET",
        url:module_name+"/Orgnizer/getClassInfoTree",
        dataType:"json",
        success:function(data){
            if(data.code != -1){
                push_nestable(data);
                $(".edit-area").hide();//默认编辑组织信息全部隐藏
            }

            else{
                $("#nestable").prepend('<ol class="dd-list" id="outer-list"></ol>');
               // $("#outer-list").html('');
                alert("还没有添加过组织结构信息，可以从表格批量导入用户或者手动添加:)");
                $("#edit-classinfo").hide();
                $("#save-classinfo").show();
                //$(".edit-area").hide();
            }


        },error: function (jqXHR) {
            alert("读取组织列表信息failed"+jqXHR.status);
        }
    });

    //读取组织名

    $.ajax({
        type:"GET",
        url:module_name+"/Orgnizer/getOrgName",
        dataType:"json",
        success:function(data){
            $("#org-name").val(data);
        },error: function (jqXHR) {
            alert("failed"+jqXHR.status);
        }
    });



    $("#save-classinfo").hide();//保存按钮隐藏
    $("#add-user-btn").hide();//当选择了子级了才显示按钮



    $(document).on('click', '#edit-classinfo', function(){
        $(".edit-area").show();
        $("#edit-classinfo").hide();
        $("#save-classinfo").show();
    });

    var updateOutput = function (e) {
        var list = e.length ? e : $(e.target),
            output = list.data("output");
        if (window.JSON) {
            output.text(window.JSON.stringify(list.nestable("serialize"))); //, null, 2));
        } else {
            output.text("JSON browser support required for this demo.");
        }
    };


    function updateClassInfo (){
        updateOutput($("#nestable").data("output", $("#nestable-output")));
        $.ajax({
            type: "POST",
            url: module_name+"/Orgnizer/updateClassInfo",
            dataType: "json",
            async: false,
            data: {
                class_info:$("#nestable-output").text()
            },
            success: function (data) {
                alert(data.msg);
                location.reload();

            }, error: function (jqXHR) {
                alert("保存列表failed" + jqXHR.status);
            }
        });
    }

    $("#save-classinfo").click(updateClassInfo);


    // output initial serialised data
    updateOutput($("#nestable").data("output", $("#nestable-output")));


    $("#nestable-menu").on("click", function (e) {
        var target = $(e.target),
            action = target.data("action");
        if (action === "expand-all") {
            $(".dd").nestable("expandAll");
        }
        if (action === "collapse-all") {
            $(".dd").nestable("collapseAll");
        }
    });


    //add class添加父级项目
    $(document).on('click', '#submit-class', function(){
        var status = 1;
        var str = $("#class-inputval").val();

        //判空
        if (!str){
            alert("输入不能为空！");
            return false;
        }

        $("#outer-list >li").each(function(){
            if ($(this).attr("data-id") == str)
            {
                alert($(this).attr("data-id")+"名称重复！") ;
                status = 0;
                return false;
            }

        });


        if (status == 0)
            return false;
        var htmls = ['<li class="dd-item" data-id="'+str+'">'];
        htmls.push('<div class="dd-handle">'+str+'<a class="btn btn-primary btn-sm btn-parsley add-subclass edit-area">添加二级子级</a></div>');
        htmls.push('</li>');
        $("#outer-list").append(htmls.join(''));
        updateOutput($("#nestable").data("output", $("#nestable-output")));


        $(document).off('click', '.dd-item');//输入时不获取class信息

    });//添加一级项目

    $(document).on('click', '.submit-subclass', function(){

        var status = 1;

        var str = $(this).parent().find('input').val();

        //判空
        if (!str){
            alert("输入不能为空！");
            return false;
        }

        //判断二级列表项目有没有重复元素 有就返回不添加
        $(this).parent().parent().find('li').each(function(){
            if($(this).attr("data-id") == str){
                alert($(this).attr("data-id")+"名称重复了！");
                status = 0;
                return false;
            }
        });
        if (status == 0)
            return false;
        var htmls = ['<li class="dd-item" data-id="'+str+'">'];
        htmls.push('<div class="dd-handle">'+str+'</div>');
        htmls.push('</li>');

        $(this).parent().parent().parent().find('ol').prepend(htmls.join(''));
        updateOutput($("#nestable").data("output", $("#nestable-output")));

    });//添加二级项目

    $(document).on('click', '.add-subclass', function(){

        var htmls = [''];
        $(this).parent().find('a').hide();
        htmls.push('<ol class="dd-list" style="">');
        htmls.push('<div class="edit-area" > <input type="text" class="form-control addclass class-subinputval mg-b-lg"  placeholder="输入级别名称（如班级，部门名）"  /><a class="btn btn-primary btn-sm btn-parsley submit-subclass" id="">添加子级</a> </div></ol>');
        $(this).parent().parent().append(htmls.join(''));
    });

    //默认显示全部用户

    table.showtable();



    $(document).on('click', ".delete-classlevel", function(){

        //ajax...

        var $item = $(this);

        $.ajax({
            type: "POST",
            url: module_name+"/Orgnizer/deleteClass",
            dataType: "json",
            async: false,
            data: {
                class_name:$item.parent().find('a').filter(".inner-classtext").text()
            },
            success: function (data) {
                alert("批量删除用户成功！");

                $item.parent().parent().find('ol').remove();
                $item.parent().parent().remove();
                //alert("更新列表");
                updateClassInfo();

            }, error: function (jqXHR) {
                alert("删除项目failed" + jqXHR.status);
            }
        });

    });




    $(document).on('click', '.dd-item', function (e) {//左边组织结构标签栏选择事件

        e.stopPropagation();//阻止冒泡
        var i = 0;
        var arr = [];
        arr[i] = $(this).attr('data-id');
        i++;
        var parent = $(this).parent().parent().attr('data-id');
        if (parent){
            arr[i] = parent;
        }
        arr = arr.reverse();
        if (arr.length == 1){
            $("#add-user-btn").hide();
            console.log('一级项不能选择');//作为一级项不添加用户信息
            return;
        }
        else{
            $("#add-user-btn").show();
        }
        var json = {};
        for (i = 0; i <= arr.length ; i++){
            json['class_'+ (i + 1)] = arr[i];
        }
        json = JSON.stringify(json);
        var json_arr = [];
        json_arr.push(json);
        if (e.target.innerText == '删除该级'){

            if(confirm("确认删除该组及其下面所有用户么")){
                var $e = $(e.target);
                $("#nestable-output").text();
                $e.parent().parent().remove();

                //alert("ajax删除事件:" + json);
                $.ajax({
                    type:"POST",
                    url:module_name+"/Orgnizer/deleteSubClass",
                    dataType:"json",
                    data:{
                        classJson:json
                    },
                    success:function(data){
                        alert("这个项目的用户删除"+data.msg);
                        updateOutput($("#nestable").data("output", $("#nestable-output")));
                        //alert($("#nestable-output").text());
                        //保存组织信息

                        updateClassInfo();

                        //$.ajax({
                        //    type: "POST",
                        //    url: module_name+"/Orgnizer/updateClassInfo",
                        //    dataType: "json",
                        //    async: false,
                        //    data: {
                        //        class_info:$("#nestable-output").text()
                        //    },
                        //    success: function (data) {
                        //        alert("组织信息状态：" + data.msg);
                        //        location.reload();
                        //
                        //    }, error: function (jqXHR) {
                        //        alert("删除项目failed" + jqXHR.status);
                        //    }
                        //});

                    },error: function (jqXHR) {
                        alert("这个项目的用户删除failed"+jqXHR.status);
                    }
                });
            }
            else{
                alert("操作已取消");
            }



        }
        else{
            $("#add-user-classinfo").html(json_arr);
            //查到的用户添加到表格中去
            table.showtable();
        }

    });


    $(document).on('click', '.delete-subclasslevel', function(){
       //alert($(this).html());

    });


    $("#delete-user").click(function(){

        if (confirm("确认删除所选用户么")){
            $.ajax({
                type:"POST",
                url:module_name+"/Orgnizer/deleteUsers",
                dataType:"json",
                data:{
                    userlist:JSON.stringify($('#user-list-table').bootstrapTable('getSelections'))
                },
                success:function(data){
                    alert(data.msg);
                    table.showtable();

                },error: function (jqXHR) {
                    alert("failed"+jqXHR.status);
                }
            });
        }


    });


    /**
     * 显示用户列表（使用bstable插件）
     * @param click_para(搜索参数)
     */

    function Bstable(){

        function ClickRowQueryParams(para){//返回选定班级信息的人员信息查询json数组
            var querydata = {
                searchkey:$("#add-user-classinfo").html()
            };
            return querydata;
        }

        function columns(){//表格列信息
            return [
                {
                    field: 'state',
                    checkbox: true
                },{
                    field:'uid',
                    title:'uid'
                },{
                    field:'username',
                    title:'用户名',
                    formatter:Formatter
                },{
                    field:'email',
                    title:'邮箱',
                    formatter:Formatter
                },{
                    field:'class',
                    title:'组织信息',
                    formatter:Formatter
                }];
        }

        function Formatter(value, row, index)
        {
            return '<a href="#">'+value+'</a>';
        }

        function stateFormatter(value, row, index) {//复选框处理方法

            if (row.id === 2) {
                return {
                    disabled: true,
                    checked: true
                };
            }
            if (row.uid === 0) {
                return {
                    disabled: true,
                    checked: true
                }
            }
            return value;
        }

        function onClickRow(row){//点击用户信息行弹出修改用户信息对话框

            $("#edit-uid").html(row.uid);
            $("#edit-username").val(row.username);
            $("#edit-useremail").val(row.email);

            $("#row_username").html(row.username);
            $("#row_useremail").html(row.email);

            $("#edit-user").modal('show');

        }

        this.showtable = function(){
            var tabletool = new TableTools();
            tabletool.bstable("user-list-table", module_name+"/Orgnizer/getUserList", columns(), ClickRowQueryParams, onClickRow);
        };

    }

    //保存编辑的用户
    $(document).on('click', '#edit-user-save', function(){
        alert("start edit"+$("#row_username").html());

        var username;
        var useremail;

        ($("#edit-username").val() == $("#row_username").html())?username='':username = $("#edit-username").val();
        ($("#edit-useremail").val() == $("#row_useremail").html())?useremail='':useremail = $("#edit-useremail").val();

        $.ajax({
            type:"POST",
            url:module_name+"/Orgnizer/updateUserInfo",
            dataType:"json",
            async : false,
            data:{
                uid:$("#edit-uid").html(),
                username:username,
                useremail:useremail,
                userpassword:$("#edit-userpassword").val()
            },
            success:function(data){
                alert(data.msg);
                table.showtable();
                $("#edit-user").modal('hide');

            },error: function (jqXHR) {
                alert("failed"+jqXHR.status);
            }
        });
    });


    //新增user对话框
    $("#add-user-btn").click(function(){
        $("#add-user").modal('show');
    });

    $("#add-user-newrow").click(function(){
        var htmls = ['<tr>'];
        htmls.push('<td>'+$("#add-username").val()+'</td>');
        htmls.push('<td>'+$("#add-userpasswd").val()+'</td>');
        htmls.push('<td>'+$("#add-useremail").val()+'</td>');
        htmls.push('<td>' + $("#add-userage").val()+'</td>');
        htmls.push('<td>' + $("input[name='sex']:checked").val()+'</td>');
        htmls.push('<td><a class="btn btn-danger add-rowdelete">删除</a></td></tr>');
        $("#add-user-tbody").prepend(htmls.join(''));
    });

    $(document).on('click', '.add-rowdelete', function(){
        $("#add-user-tbody tr").eq($(this).parent().parent().index()).remove();
    });

    $("#add-user-save").click(function(){

        var arr = [];
        var i = 0;

        $("#add-user-tbody tr").each(function(){
            arr.push([]);
            $(this).find('td').each(function(){
                arr[i].push($(this).text());
            });
            i ++;
            //用$(this)可以访问正在循环的元素
        });


        var json = {};
        var k = 0;

        for (i = 0; i< arr.length - 1; i++){
            json[k] = {};
            json[k]['username'] = arr[i][0];
            json[k]['password'] = arr[i][1];
            json[k]['email'] = arr[i][2];
            json[k]['age'] = arr[i][3];
            json[k]['sex'] = arr[i][4];
            k++;
        }

        var j = [];
        j.push(json);

        var jsondata = JSON.stringify(j);
        //console.log(jsondata);

        $.ajax({
            type:"GET",
            url:module_name+"/Orgnizer/addJsonUserData",
            dataType:"json",
            async : false,
            data:{
                jsondata:jsondata,
                classinfo:$("#add-user-classinfo").html()
            },
            success:function(data){
                alert(data.msg);
                table.showtable();
               // bstable($("#add-user-classinfo").html());
            },error: function (jqXHR) {
                alert("failed"+jqXHR.status);
            }
        });

    });

    function push_nestable(data)//恢复读取的组织信息
    {
        $('#nestable').nestable('destroy');
        $("#outer-list").html('');
        var htmls = [''];
        htmls.push('<ol class="dd-list" id="outer-list">');
        for(var i = 0; i < data.length; i++){
            htmls.push('<li class="dd-item" data-id="'+data[i].id+'">');
            if(data[i].children)
                htmls.push('<div class="dd-handle"><a href="#" class="inner-classtext">'+data[i].id+'</a><a class="btn btn-danger btn-sm pull-right mg-b-sm edit-area delete-classlevel ">删除父级</a></div> ');
            else
                htmls.push('<div class="dd-handle">'+data[i].id+'<a class="btn btn-primary btn-sm btn-parsley add-subclass edit-area">添加二级子级</a></div> ');

            if(data[i].children){
                htmls.push('<ol class="dd-list">');
                for (var j=0; j < (data[i].children).length; j++){
                    htmls.push('<li class="dd-item" data-id="'+data[i].children[j].id+'">');
                    htmls.push('<div class="dd-handle"><a href="#">'+data[i].children[j].id+'</a><a class="btn btn-danger btn-sm pull-right mg-b-sm edit-area delete-subclasslevel">删除该级</a></div> </li>');
                }
                htmls.push('<div class="edit-area"> <input type="text" class="form-control addclass class-subinputval mg-r-sm"  placeholder="输入级别名称（如班级，部门名）"  /><a class="btn btn-primary btn-sm btn-parsley submit-subclass" id="">添加子级</a> </div>');
                htmls.push('</ol>');

            }
            htmls.push('</li>');

        }
        htmls.push('</ol>');

        $("#nestable").prepend(htmls.join(''));

        $('#nestable').nestable('init');
        $("#nestable").nestable({
            group: 1
        }).on("change", updateOutput);

    }




    //上传xls部分


    $("#import-xls-all-btn").click(function(){
        $("#xls-upload-all").trigger('click');
    });
    $("#xls-upload-all").change(function(){

        var fd = new FormData();
        //console.log($("#xls-upload-all")[0].files[0]);
        fd.append( 'file', $("#xls-upload-all")[0].files[0] );


        $.ajax({
            url: module_name+'/Orgnizer/xlsImportUserAll' ,
            type: 'POST',
            data: fd,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function (returndata) {
                alert(returndata.msg);
                location.reload();
            },
            error: function (returndata) {
                alert("上传文件失败："+returndata.jqXHR);

            }
        });


    });




}

$(document).ready(function () {

});